﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BookingDB.Models;
using GenericModels;

namespace CTRLayer
{
    public class CTRCity
    {
        private BioBookingContext db;

        public CTRCity()
        {
            db = new BioBookingContext();
        }

        /// <summary>
        /// Used to add a city to the database
        /// </summary>
        /// <param name="postalCode"></param>
        /// <param name="cityName"></param>
        public void AddCityToDB(int postalCode, string cityName)
        {
            EntityCity city = new EntityCity() {postalCodeID = postalCode, cityName = cityName};
            db.Cities.Add(city);
            db.SaveChanges();
        }

        /// <summary>
        /// Used to retrieve a city from the db using the postal code
        /// </summary>
        /// <param name="postalCode"></param>
        /// <returns></returns>
        public City RetrieveCity(int postalCode)
        {
            EntityCity cityEntity = (from c
                               in db.Cities
                               where c.postalCodeID == postalCode
                               select c).FirstOrDefault();

            return TranslateCity(cityEntity);
        }


        /// <summary>
        /// Retrieves all the cities which are stored in the database.
        /// unsorted
        /// </summary>
        /// <returns>A list of cities</returns>
        public List<City> RetrieveAllTheCities()
        {
            List<City> cities = new List<City>();
            IQueryable<EntityCity> eCities = (from c in db.Cities select c);

            foreach (EntityCity ec in eCities)
            {
                cities.Add(TranslateCity(ec));
            }

            return cities;
        }


        /// <summary>
        /// Helper method, which translates the retrieved entity framework object of a city, into a generic model
        /// </summary>
        /// <param name="eCity"></param>
        /// <returns></returns>
        private City TranslateCity(EntityCity eCity)
        {
            City city = new City();

            city.PostalCode = eCity.postalCodeID;
            city.CityName = eCity.cityName;
            return city;
        }
    }
}
